<template>
  <el-row>

    <el-col :span="12">
      <s-info
        :data="infoData"
        :form-loading="infoLoading"
        :methods="methods"
        :statement="statement"
      >
      </s-info>
    </el-col>
    <el-col :span="12">
      <div class="view-info-container" v-if="editor" v-loading="infoLoading">
        <SJsonEditor v-model="jsonData" @change="handleJsonChange" :schema-type="schemaType" />
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import SJsonEditor from '@/components/SJsonEditor.vue'
import SInfo from '@/components/common/info/SInfo.vue'
import { useInfo } from '@/composables/info-composable'
import type { ResultData } from '@/api/service'
import { saveViewApi, viewInfoApi } from '@/api/view'
import type { ViewVo } from '@/type/common/view-types'
import { ElNotification } from 'element-plus'

const props = defineProps<{
  query: { viewId?: string }
}>()

const { statement, infoLoading, infoData, isNew } = useInfo<ViewVo>('ViewInfo', getData)
const editor = ref<Boolean>(false)

const schemaType = ref<string>('List')
function getData() {
  if (props.query.viewId !== undefined) {
    infoLoading.value = true
    isNew.value = false
    // 页面传递userId, 调用接口查询数据回显
    viewInfoApi(props.query.viewId).then((response: ResultData<ViewVo>) => {
      infoData.value = response.data
      jsonData.value = response.data.content
      schemaType.value = infoData.value.viewType
      editor.value = true
      infoLoading.value = false
    })
  } else {
    editor.value = true
  }
}

const methods = {
  save: () => {
    const viewDto: ViewVo = {
      viewName: infoData.value.viewName,
      viewType: infoData.value.viewType,
      content: jsonData.value,
      version: infoData.value.version,
      viewKey: infoData.value.viewKey
    }
    if (!isNew.value) {
      viewDto.viewId = infoData.value.viewId
    }
    saveViewApi(viewDto).then(() => {
      ElNotification.success({
        title: '成功',
        message: '保存视图',
        type: 'success'
      })
    }).catch((err) => {
      if (err.code === 438) {
        validErrors(err.data)
      }
    })
  }
}

const jsonData = ref<string>('')
const isJsonValid = ref(true)
// 处理 JSON 变化
const handleJsonChange = (value: string, isValid: boolean) => {
  isJsonValid.value = isValid
}
</script>

<style scoped>
.view-info-container {
  padding: 0 20px;
  height: 700px;
}
</style>
